package com.online.edu.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.online.edu.course.entity.Category;
import com.online.edu.course.entity.CategoryMapping;
import com.online.edu.course.entity.Course;
import com.online.edu.course.entity.Vo.CategoryVo;
import com.online.edu.course.mapper.CategoryMapper;
import com.online.edu.course.service.ICategoryMappingService;
import com.online.edu.course.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.online.edu.course.service.ICourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类表 服务实现类
 * </p>
 *
 * @author world
 * @since 2021-07-30
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryService categoryService;

    @Autowired
    ICategoryMappingService categoryMappingService;

    @Autowired
    ICourseService courseService;

    @Override
    public List<CategoryVo> listWithTree() {
        List<Category> entities = list();

        //把Category的数组entities包装成CategoryVo数组
        List<CategoryVo> categoryVos = entities.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());


        //filter取得所有parentId为0的数据，也就是一级目录
        //map用于封装数据，取得他的孩子（也就是下级目录）的数据
        List<CategoryVo> list = categoryVos.stream()
                .filter(category -> category.getParentId().equals(Long.parseLong("0")))//parentId为0则说明该节点为根节点
                .map(
                        (menu)->{
                            menu.setChildren(getChildrenData(menu,categoryVos));
                            return menu;
                        })
                .collect(Collectors.toList());
        return list;
    }

    //递归删除分类
    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public boolean delCategory(long id) throws Exception {
        //先通过分类id获取分类
        Category category = categoryService.getById(id);
        //获取该分类的parentId
        long parentId = category.getId();
        //判断该分类是否关联课程
        QueryWrapper<CategoryMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",id);
        CategoryMapping categoryMapping = categoryMappingService.getOne(wrapper);
        if (!StringUtils.isEmpty(categoryMapping)){
            Course course = courseService.getById(categoryMapping.getCourseId());
            if (!StringUtils.isEmpty(course)){
                //如果有课程关联，则删除失败，抛出异常
                throw new Exception("删除失败");
            }
            else {
                //否则删除分类关联
                categoryMappingService.removeById(categoryMapping.getCategoryMapping());
                categoryService.removeById(id);
                //判断是否还有子分类
                if (parentId != 0){
                    //如果含有子分类
                    QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("parent_id",parentId);
                    //获取子分类
                    Category categoryChildren = categoryService.getOne(queryWrapper);
                    if (!StringUtils.isEmpty(categoryChildren)){
                        id = categoryChildren.getId();
                        //boolean b = categoryService.removeById(categoryChildren.getId());
                        delCategory(id);
                    }
                }
                return true;
            }
        }
        else {
            //否则直接删除该分类
            categoryService.removeById(id);
            //判断是否还有子分类
            if (parentId != 0){
                //如果含有子分类
                QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id",parentId);
                //获取子分类
                Category categoryChildren = categoryService.getOne(queryWrapper);
                if (!StringUtils.isEmpty(categoryChildren)){
                    id = categoryChildren.getId();
                    //boolean b = categoryService.removeById(categoryChildren.getId());
                    delCategory(id);
                }
            }
            return true;
        }
    }

    //获取孩子（下级目录）的方法，递归实现
    private List<CategoryVo> getChildrenData(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        List<CategoryVo> children = categoryVoList.stream()
                .filter(c -> c.getParentId().equals(categoryVo.getId()))
                .map(
                        c -> {
                            c.setChildren(getChildrenData(c,categoryVoList));
                            return c;
                        })
                .collect(Collectors.toList());
        return children;
    }
}
